using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Infrastructure.Services.Database;

namespace JGSY.CMS.LowCode.Platform.Controllers
{
    /// <summary>
    /// 数据库状态检查控制器
    /// 用于测试延迟数据库连接功能
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class DbStatusController : ControllerBase
    {
        private readonly ILazyDbContextFactory _dbFactory;
        private readonly ILogger<DbStatusController> _logger;

        public DbStatusController(
            ILazyDbContextFactory dbFactory,
            ILogger<DbStatusController> logger)
        {
            _dbFactory = dbFactory;
            _logger = logger;
        }

        /// <summary>
        /// 获取数据库连接状态
        /// </summary>
        [HttpGet("status")]
        public IActionResult GetDbStatus()
        {
            try
            {
                var status = _dbFactory.GetConnectionStatus();
                var isAvailable = _dbFactory.IsDbAvailable();

                return Ok(new
                {
                    Status = "success",
                    DatabaseStatus = status,
                    IsAvailable = isAvailable,
                    Message = "数据库状态检查完成"
                });
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "数据库状态检查失败");
                return Ok(new
                {
                    Status = "error",
                    DatabaseStatus = "检查失败",
                    IsAvailable = false,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// 触发数据库连接初始化
        /// </summary>
        [HttpPost("initialize")]
        public IActionResult InitializeDb()
        {
            try
            {
                var startTime = System.DateTime.UtcNow;
                var dbContext = _dbFactory.CreateDbContext();
                var elapsed = (System.DateTime.UtcNow - startTime).TotalMilliseconds;

                _logger.LogInformation("[DbStatus] 数据库初始化耗时: {Elapsed}ms", elapsed);

                return Ok(new
                {
                    Status = "success",
                    InitializationTime = $"{elapsed}ms",
                    DatabaseProvider = dbContext.Database.ProviderName,
                    Message = "数据库初始化完成"
                });
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "数据库初始化失败");
                return StatusCode(503, new // 503 Service Unavailable
                {
                    Status = "error",
                    InitializationTime = "N/A",
                    DatabaseProvider = "N/A",
                    Message = $"数据库不可用: {ex.Message}"
                });
            }
        }
    }
}
